package cn._51doit.log;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

public class LogUtil {

    public static void main(String[] args) throws Exception{

        String filePath = args[0];
        String offsetPath = args[1];

        long offset = 0;
        //读取一个文件的内容
        RandomAccessFile file = new RandomAccessFile(filePath, "r");
        //获取以前的偏移量
        File offsetFile = new File(offsetPath);
        String offsetStr = FileUtils.readFileToString(offsetFile);
        if (offsetStr != null && !"".equals(offsetStr)) {
            offset = Long.parseLong(offsetStr);
        }
        //从值得的偏移量读取数据
        file.seek(offset);

        while (true) {
            String line = file.readLine();
            if (line != null) {
                line = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                System.out.println(line);
                //TODO 将数据写入到Kafka
                //获取最新的偏移量
                offset = file.getFilePointer();
                //更新偏移量
                FileUtils.writeStringToFile(offsetFile, String.valueOf(offset));
            } else {
                Thread.sleep(1000);
            }
        }

    }
}
